package com.wasion.pwportable.jsi;

import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.wasion.core.db.storage.SqliteStorage;
import com.wasion.core.db.storage.SqliteStorageListener.DataQueryListener;
import com.wasion.core.db.storage.StorageQuery;
import com.wasion.core.util.DateTimeUtil;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.activity.PwPortableActivity;
import com.wasion.pwportable.dao.sd.IndicatorSDDBDao;
import com.wasion.pwportable.dao.sd.IndicatorStatusSDDBDao;
import com.wasion.pwportable.domain.po.Indicator;
import com.wasion.pwportable.domain.po.IndicatorStatus;
import com.wasion.pwportable.domain.po.IndicatorStatus.ComparatorIndicator;

/**
 * 
 * @ClassName: IndicatorStatusJSI
 * @Description: 指示器状态JavaScriptInterface，对指示器状态操作交互接口<br/>
 *               1. 增加/修改指示器状态 <br/>
 *               2. 获取指示器状态集合 <br/>
 * @author 高意
 * @date 2014-8-1 下午2:57:06
 * 
 */
public class IndicatorStatusJSI {

	// 应用上下文
	private Context context;

	// webview，浏览器窗口
	private WebView webView;

	// Sqlite存储实例
	private SqliteStorage sqliteStorage = null;

	// Google的Json转换工具
	private Gson gson = new Gson();

	// 指示器状态数据库访问接口
	private IndicatorStatusSDDBDao indicatorStatusSDDBDao = null;

	public IndicatorStatusJSI(Context context) {
		this.context = context;
		this.webView = PwPortableActivity.getWebView();
		this.sqliteStorage = SqliteStorage.getInstance(this.context);
		indicatorStatusSDDBDao = new IndicatorStatusSDDBDao(context);
	}

	/**
	 * 
	 * @Title: addOrModifyIStatus
	 * @Description: 新增/修改指示器状态
	 * @param
	 * @return
	 * @throws
	 */
	public void addOrModifyIStatus(final String jsonStr) {

		PwPortableActivity.getHandler().post(new Runnable() {

			public void run() {

				try {

					JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
					String indicatorAddr = json.get("indicatorAddr")
							.getAsString();
					String time = DateTimeUtil.getCurrentDate();

					// 1. 根据指示器地址查询ID
					IndicatorSDDBDao indicatorSDDBDao = new IndicatorSDDBDao(
							context);
					indicatorSDDBDao.startReadableDatabase(false);
					List<Indicator> indicators = indicatorSDDBDao.queryList(
							"UPPER(indicatoraddr)=?",
							new String[] { indicatorAddr.toUpperCase() });
					indicatorSDDBDao.closeDatabase(false);

					if (0 == indicators.size()) {
						return;
					}
					Indicator indicator = indicators.get(0);
					int indicatorId = indicator.get_id();

					// 2. 判断指示器ID下是否有状态记录
					indicatorStatusSDDBDao.startReadableDatabase(false);
					List<IndicatorStatus> statuses = indicatorStatusSDDBDao
							.queryList("_id=?",
									new String[] { indicatorId + "" });
					indicatorStatusSDDBDao.closeDatabase(false);

					// 3. 如果存在，则修改；如果不存在则新增
					indicatorStatusSDDBDao.startReadableDatabase(false);
					if (null == statuses || 0 == statuses.size()) { // 新增

						IndicatorStatus status = new IndicatorStatus();
						status.setIndicatorid(indicatorId);

						status.setTerminalid(indicator.getTerminalid());
						status.setTime(time);
						if (null != json.get("singleComm")) {
							status.setSinglecomm(json.get("singleComm")
									.getAsInt());
						}
						if (null != json.get("multiComm")) {
							status.setMulticomm(json.get("multiComm")
									.getAsInt());
						}
						if (null != json.get("network")) {
							status.setNetwork(json.get("network").getAsInt());
						}
						indicatorStatusSDDBDao.insert(status);
					} else { // 修改

						StringBuffer buffer = new StringBuffer();
						if (null != json.get("singleComm")) {
							buffer.append(" singlecomm='"
									+ json.get("singleComm").getAsInt() + "',");
						}
						if (null != json.get("multiComm")) {
							buffer.append(" multicomm='"
									+ json.get("multiComm").getAsInt() + "',");
						}
						if (null != json.get("network")) {
							buffer.append(" network='"
									+ json.get("network").getAsInt() + "',");
						}

						buffer.append(" time='" + time + "'");
						indicatorStatusSDDBDao.execSql(
								"update indicator_status set"
										+ buffer.toString() + " where _id=?",
								new String[] { indicatorId + "" });
					}
					indicatorStatusSDDBDao.closeDatabase(false);
				} catch (Exception e) {
					JSIHelper.showToast(context, "系统发生异常!");
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 
	 * @Title: queryIndicatorStatuses
	 * @Description: 获取終端下的所有指示器状态
	 * @param
	 * @return
	 * @throws
	 */
	public void queryIndicatorStatuses(final String terminalid) {

		StorageQuery storageQuery = new StorageQuery();

		if (!StringUtil.isEmpty(terminalid)) {
			storageQuery.equals("terminalid", terminalid);
		}
		//storageQuery.addSort("time", SortOrder.DESC);

		sqliteStorage.findData(storageQuery, indicatorStatusSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询指示器状态失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							try {
								// 根据组号、相位排序
								List<IndicatorStatus> list = (List<IndicatorStatus>)paramList;
								ComparatorIndicator comparator = new IndicatorStatus().new ComparatorIndicator();
								Collections.sort(list, comparator);
								
								String jsonStr = gson.toJson(paramList);

								webView.loadUrl("javascript:queryIndicatorStatusesCallback("
										+ jsonStr + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						}
					}
				});
	}
}
